package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.dialog.PackageDialog;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.FormatUtil;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.ProductAddEntity;
import com.epfresh.supplier.entity.TagPackage;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzh on 16-7-25.
 */
public class ProductPackageActivity extends BaseActivity {


    private TextView tvPackageUnit;
    private ImageView ivPackageUnit;
    private TextView tvWeightUnit;
    private EditText edPackage;
    private EditText edWeight;
    private View vWeight;
    private View rlPackageTips;

    private TextView tvBtn;


    private TagPackage tagPackage;

    private String packageUnit;
    private String packageContainer;
    private String chargeUnit;

    private List<String> priceUnit = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null){
            getIntent().putExtra("dataProduct", savedInstanceState.getString("dataProduct"));
            String dataProduct = getIntent().getStringExtra("dataProduct");
            if(dataProduct != null && !"".equals(dataProduct)) {
                DataManager.getInstance().setProductAddEntity(new Gson().fromJson(dataProduct,ProductAddEntity.class));
            }
        }

        setContentView(R.layout.activity_product_package);

        findViewById(R.id.ll_btn).setVisibility(View.GONE);
        tvBack.setVisibility(View.VISIBLE);

        ivBack.setVisibility(View.VISIBLE);
        String s = "包装 <font color=\"#ff0000\">*</font>";
        toolbarTitle.setText(Html.fromHtml(s));

        rightbtn.setText("确定");

        rightbtn.setVisibility(View.VISIBLE);

        rightbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextView();
            }
        });

        tvWeightUnit = (TextView) findViewById(R.id.tv_package_unit);

        edPackage = (EditText) findViewById(R.id.ed_package);

        edWeight = (EditText) findViewById(R.id.ed_weight);

        vWeight = findViewById(R.id.rl_weight);
        rlPackageTips = findViewById(R.id.rl_refuse_reason);

        tvBtn = (TextView) findViewById(R.id.tv_btn);

        tvBtn.setOnClickListener(this);
        tvPackageUnit = (TextView) findViewById(R.id.tv_package);

        ivPackageUnit = (ImageView) findViewById(R.id.iv_flag);

        tvPackageUnit.setOnClickListener(this);
        ivPackageUnit.setOnClickListener(this);


        String packageSize = getIntent().getStringExtra("packageSize");
        packageUnit = getIntent().getStringExtra("unit");
        packageContainer = getIntent().getStringExtra("container");
        String weight = getIntent().getStringExtra("weight");

        edPackage.setText(packageSize);

        edPackage.setSelection(edPackage.length());
        if (weight != null && !"".equals(weight)) {
            edWeight.setText(FormatUtil.subZeroAndDot(weight));
        }else {
            edWeight.setText("");

        }


        String tagPackageStr = getIntent().getStringExtra("tagPackage");

        if (tagPackageStr != null) {
            tagPackage = new Gson().fromJson(tagPackageStr, TagPackage.class);
        }

        if (tagPackage == null) {
            return;
        } else if (packageUnit == null || "".equals(packageUnit)) {

            List<String> container = tagPackage.getContainer();
            List<String> unit = tagPackage.getUnit();
            if (container != null && container.size() > 0) {
                packageContainer = container.get(0);
            }

            if (unit != null && unit.size() > 0) {
                packageUnit = unit.get(0);
            }
        }

        tvPackageUnit.setText(packageUnit + "/" + packageContainer);

        CashierInputFilter filter = new CashierInputFilter();
        filter.MAX_VALUE = 99999999;
        edPackage.setFilters(new InputFilter[]{filter});
//        CashierInputFilter filter = new CashierInputFilter();
//        filter.MAX_VALUE = 99999999;
        edWeight.setFilters(new InputFilter[]{filter});

        updateProductStatus(packageUnit, packageContainer);
        if(getIntent()!=null&&getIntent().getBooleanExtra("isAlready",false)){
            Log.e("________","just buke");
            edPackage.setEnabled(false);
        }

        initNextView();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();
        if(productAddEntity != null) {
            outState.putString("dataProduct", new Gson().toJson(productAddEntity));
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    public void finish() {
        super.finish();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘
    }

    private TextView tvPre;
    private TextView tvNext;

    private void initNextView() {
        tvNext = (TextView) findViewById(R.id.tv_next);
        tvPre = (TextView) findViewById(R.id.tv_pre);

        tvPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                preView();
            }
        });
        tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                nextView();
            }
        });
    }

    private void preView() {
        finish();
    }

    private void nextView() {

        Editable text = edPackage.getText();
        if (text.length() < 1) {
            toast("请输入包装");
            return;
        }
        String s1 = text.toString().replace("0","");
        s1 = s1.toString().replace(".","");
        if("".equals(s1)){
            toast("请输入大于0的包装");
            return;
        }

        if (vWeight.getVisibility() == View.VISIBLE  ) {
            String s = edWeight.getText().toString();
            if ( s.length() < 1) {
                toast("请输入重量");
                return;
            }else if ("0".equals(s) || "0.0".equals(s)|| "0.00".equals(s)){
                toast("请输入大于0的重量");
                return;
            }else {
                s1 = s.replace("0","");
                s1 = s1.toString().replace(".","");
                if("".equals(s1)){
                    toast("请输入大于0的重量");
                    return;
                }
            }
        } else if (vWeight.getVisibility() != View.VISIBLE) {

            String s = text.toString();
            double f = Double.valueOf(s);
            if ("斤".equals(packageUnit)) {
                s = f / 2.0 + "";
            } else if ("吨".equals(packageUnit)) {
                s = f * 1000 + "";
            } else if ("克".equals(packageUnit)) {
                double v = f / 1000.0;
                s = v + "";
            }


            edWeight.setText(FormatUtil.subZeroAndDot(s,3));
        }
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘
        Intent intent = new Intent();
        intent.putExtra("packageSize", edPackage.getText().toString());
        intent.putExtra("unit", packageUnit);
        intent.putExtra("chargeUnit", chargeUnit);
        intent.putExtra("container", packageContainer);
        Log.e("weight",edWeight.getText().toString());
        Log.e("chargeUnit",chargeUnit);
        intent.putExtra("weight", edWeight.getText().toString());
        intent.putExtra("isModify",true);
        intent.putExtra("priceUnit", new Gson().toJson(priceUnit));
        setResult(RESULT_OK, intent);
        finish();

       /* ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();
        productAddEntity.setPackageSize(text.toString());
        productAddEntity.setPackageUnit(packageUnit);
        productAddEntity.setPackageContainer(packageContainer);
        productAddEntity.setWeight(edWeight.getText().toString());
        productAddEntity.setChargeUnit(chargeUnit);

        productAddEntity.setPriceUnit(new Gson().toJson(priceUnit));

        setResult(RESULT_OK);
        finish();*/
       /* Intent intent = new Intent(this, ProductAddOtherActivity.class);
        intent.putExtra("page_type", "3");
        intent.putExtra("varietyName", productAddEntity.getVariety());
        intent.putExtra("nameId", productAddEntity.getNameId());
        intent.putExtra("tagPackage", getIntent().getStringExtra("tagPackage"));
        startActivity(intent);*/

    }


    @Override
    public void onRightClick() {
//        save();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {

            case R.id.rightbtn:

                break;
            case R.id.tv_btn:
                nextView();
                break;

            case R.id.iv_flag:
            case R.id.tv_package:
                if(getIntent()!=null&&getIntent().getBooleanExtra("isAlready",false)){
                    toast("本商品无法修改此项");
                    return;
                }
                openUnit();
                break;


        }
    }

    private void save() {

        if (edPackage.getText().length() < 1) {
            toast("请输入包装");
            return;
        }


        if (vWeight.getVisibility() == View.VISIBLE && edWeight.getText().length() < 1) {
            toast("请输入重量");
            return;
        } else if (vWeight.getVisibility() != View.VISIBLE) {

            String s = edPackage.getText().toString();
            double f = Double.valueOf(s);
            if ("斤".equals(packageUnit)) {
                s = f / 2.0 + "";
            } else if ("吨".equals(packageUnit)) {
                s = f * 1000 + "";
            } else if ("克".equals(packageUnit)) {
                s = f / 1000.0 + "";
            }


            edWeight.setText(FormatUtil.subZeroAndDot(s));
        }
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘
        Intent intent = new Intent();
        intent.putExtra("packageSize", edPackage.getText().toString());
        intent.putExtra("unit", packageUnit);
        intent.putExtra("chargeUnit", chargeUnit);
        intent.putExtra("container", packageContainer);
        Log.e("weight",edWeight.getText().toString());
        intent.putExtra("weight", edWeight.getText().toString());

        intent.putExtra("priceUnit", new Gson().toJson(priceUnit));
        setResult(RESULT_OK, intent);
        finish();
    }


    private boolean isNoPackage;

    private void openUnit() {
//        if (productId != null && !"".equals(productId)) {
//            toast("商品包装不可修改");
//        } else {
//            if (tagPackage.getUnit() != null && tagPackage.getUnit().size() > 0 && tagPackage.getContainer() != null && tagPackage.getContainer().size() > 0)
//                openUnitDialog(tagPackage.getUnit(), tagPackage.getContainer());
//        }

        List<String> unit = tagPackage.getUnit();
        List<String> container = tagPackage.getContainer();
        if (unit != null && container != null && unit.size() > 0 && container.size()>0)
        openUnitDialog(unit, container);
    }


    public void openUnitDialog(List<String> units, List<String> containers) {

        PackageDialog packageDialog = new PackageDialog(this);
        packageDialog.setPositiveDismiss(true);
        packageDialog.setOnPositiveClickListener(new PackageDialog.OnPositiveClickListener() {
            @Override
            public void onPositiveClickListener(int index1, String data1, int index2, String data2) {
                if(data1!=null&&data2!=null&&data1.equals(data2)){
                    toast("包装规格设置异常，请重新设置");
                    return;
                }

                updateProductStatus(data1, data2);

            }
        });
        packageDialog.setData(units, containers);

//        String packageUnit = productAddEntity.getPackageUnit();
//        String packageContainer = productAddEntity.getPackageContainer();

        if (!TextUtils.isEmpty(packageUnit) && !TextUtils.isEmpty(packageContainer)) {
            int index1 = 0;
            int index2 = 0;
            for (int i = 0; i < units.size(); i++) {
                if (packageUnit.equals(units.get(i))) {
                    index1 = i;
                }
            }
            for (int i = 0; i < containers.size(); i++) {
                if (packageContainer.equals(containers.get(i))) {
                    index2 = i;
                }
            }
            packageDialog.setCurrentItem(index1, index2);
        }

        packageDialog.show();
    }

    private void updateProductStatus(String data1, String data2) {
        tvPackageUnit.setText(data1 + "/" + data2);
//                productAddEntity.setPackageUnit(data1);
//                productAddEntity.setPackageContainer(data2);

        if(packageUnit != null && packageUnit.equals(data1) && packageContainer != null && packageContainer.equals(data2)){

        }else {
            edWeight.setText("");
        }
        packageUnit = data1;
        packageContainer = data2;
        priceUnit.clear();
//        edWeight.setInputType(InputType.TYPE_CLASS_NUMBER);
//        edWeight.setText("");
        if ("散货".equals(data2)) {
            isNoPackage = true;
            edPackage.setText("1");
            edPackage.setEnabled(false);


            chargeUnit = data1;
            if ("公斤".equals(data1)
                    || "千克".equals(data1) ||
                    "斤".equals(data1) ||
                    "吨".equals(data1) ||
                    "克".equals(data1)) {
                tvWeightUnit.setText(data1);
                priceUnit.add(data1);
                vWeight.setVisibility(View.GONE);
            } else {

//                if (!("公斤/" + data1).equals(tvWeightUnit.getText().toString())){
//
//                }

                tvWeightUnit.setText("公斤/" + data1);
                priceUnit.add(data1);
                if (!isDc()) {
                    priceUnit.add("公斤");
                } else {
                    //散货,非重量单位,重量可以输入小数
//                    edWeight.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
                }
                vWeight.setVisibility(View.VISIBLE);

            }
            rlPackageTips.setVisibility(View.VISIBLE);

        } else {
            chargeUnit = data2;
            rlPackageTips.setVisibility(View.GONE);
            if (isNoPackage) {
                isNoPackage = false;
                edPackage.setText("");
                edPackage.setEnabled(true);
            }
//            if (!("公斤/" + data2).equals(tvWeightUnit.getText().toString())){
//                edWeight.setText("");
//            }
            tvWeightUnit.setText("公斤/" + data2);
            if ("公斤".equals(data1) || "千克".equals(data1) || "斤".equals(data1) || "吨".equals(data1) || "克".equals(data1)) {
                vWeight.setVisibility(View.GONE);
                tvWeightUnit.setText(data1 + "/" + data2);
                priceUnit.add(data2);
                priceUnit.add(data1);
            } else {
                tvWeightUnit.setText("公斤/" + data2);
                vWeight.setVisibility(View.VISIBLE);
                priceUnit.add(data1);
                priceUnit.add(data2);
                priceUnit.add("公斤");
            }

        }


    }


}
